package xcoupon

import (
	"time"

	"gitee.com/xiaoyutab/xgotool/optional/xcache"
	"gitee.com/xiaoyutab/xgotool/optional/xlog"
	"gitee.com/xiaoyutab/xgotool/xerror"
	"gitee.com/xiaoyutab/xgotool/xnum"
	"gitee.com/xiaoyutab/xgotool/xstring"
)

// 根据关联ID获取专属优惠券ID【不含通用券】
//
//	goods_id	关联ID
//	level		关联等级
//	platform	所属平台
func Goods2ids(goods_id []uint, level uint8, platform uint) ([]uint, error) {
	if len(goods_id) == 0 {
		return nil, xerror.New("传入关联列表为空")
	}
	cache_key := xcache.Key("xcoupon.goods.ids", goods_id, level, platform)
	if xcache.Exists(cache_key) {
		mod := []uint{}
		if err := xcache.GetStruct(cache_key, &mod); err == nil {
			return mod, nil
		}
	}
	id := []uint{}
	err := _default.DB.Table(_default.WhithCoupon).
		Where("with_id IN ?", goods_id).
		Where("levels", level).
		Where("platform", platform).
		Select("coupon_id").
		Group("coupon_id").
		Find(&id).
		Error
	if err != nil {
		return nil, xlog.AE("关联优惠券查询错误", err)
	}
	if len(id) == 0 {
		return nil, xerror.New("数据库查询为空")
	}
	// 获取在领区范围内的优惠券
	oid := []uint{}
	for i := 0; i < len(id); i++ {
		inf, err := Info(id[i])
		if err != nil || // 错误不为空
			inf.ChildOver != 2 || // 子券未创建完成
			inf.Examine != 3 || // 未审核完成
			inf.Platform != platform || // 券平台和传入平台不一致
			inf.Quota-inf.TakeCount <= 0 || // 已全部领取
			inf.Status != 1 || // 状态判断
			!(inf.StartType == 1 || (inf.StartType == 2 && xstring.ToTime(inf.StartTime).Unix() <= time.Now().Unix() && xstring.ToTime(inf.EndTime).Unix() >= time.Now().Unix())) || // 领券时间判断
			xnum.InArray(inf.Type, coupon_all_goods) ||
			inf.AvtivationStatus == 1 { // 兑换码兑换
			continue
		}
		oid = append(oid, inf.Id)
	}
	if len(oid) == 0 {
		return nil, xerror.New("匹配到的优惠券列表为空")
	}
	xcache.SetStruct(cache_key, oid)
	return oid, nil
}

// 查询平台中所属的全平台券
//
//	platform	平台ID
func Platform2ids(platform uint) ([]uint, error) {
	cache_key := xcache.Key("xcoupon.platform.ids", platform)
	if xcache.Exists(cache_key) {
		mod := []uint{}
		if err := xcache.GetStruct(cache_key, &mod); err == nil {
			return mod, nil
		}
	}
	oid := []uint{}
	infs := []Coupon{}
	err := _default.DB.Table(_default.CouponTable).
		Where("platform", platform). // 所属平台
		Where("`type` IN ?", coupon_all_goods).
		Find(&infs).
		Error
	if err != nil {
		return nil, xlog.AE("关联优惠券查询错误", err)
	}
	for i := 0; i < len(infs); i++ {
		inf := infs[i]
		// 写入缓存
		xcache.SetStruct(xcache.Key("xgotool.xcoupon.info", inf.Id), inf)
		// 匹配条件
		if inf.ChildOver != 2 || // 子券未创建完成
			inf.Examine != 3 || // 未审核完成
			inf.Platform != platform || // 券平台和传入平台不一致
			inf.Quota-inf.TakeCount <= 0 || // 已全部领取
			inf.Status != 1 || // 状态判断
			!(inf.StartType == 1 || (inf.StartType == 2 && xstring.ToTime(inf.StartTime).Unix() <= time.Now().Unix() && xstring.ToTime(inf.EndTime).Unix() >= time.Now().Unix())) || // 领券时间判断
			inf.AvtivationStatus == 1 { // 兑换码兑换
			continue
		}
		oid = append(oid, inf.Id)
	}
	if len(oid) == 0 {
		return nil, xerror.New("匹配到的优惠券列表为空")
	}
	xcache.SetStruct(cache_key, oid)
	return oid, nil
}
